package top.aylan.org.filter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import top.aylan.org.Common.SystemConstants;
import top.aylan.org.entity.Category;
import top.aylan.org.service.CategoryService;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ConfigLoader implements Filter {

    private CategoryService  categoryService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        filterChain.doFilter(setConfigs((HttpServletRequest) servletRequest),servletResponse);
    }

    private HttpServletRequest setConfigs(HttpServletRequest request){
        request.setAttribute("imageService", SystemConstants.IMAGE_SERVICE);
        request.setAttribute("categoryList", getCategory(request));
        return request;
    }

    private List<Category> getCategory(HttpServletRequest request){

        ServletContext context = request.getSession().getServletContext();
        try {
            WebApplicationContext xmlWAContext = WebApplicationContextUtils.getWebApplicationContext(context);
            if(null != xmlWAContext && xmlWAContext.getBean(CategoryService.class) != null && categoryService == null ) {
                    categoryService = (CategoryService)xmlWAContext.getBean(CategoryService.class);
            }
            List < Category > list = categoryService.selectAllCategory();
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ArrayList<>();
    }
}